package cn.jas.api.gateway.jasgateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.codec.binary.Base64;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: jas-parent
 * @description:  访问控制过滤器
 * @author: chen_mx
 * @create: 2020-01-15 16:23
 **/

@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() {
        /** 校验用户token **/
        RequestContext  context=RequestContext.getCurrentContext();
        HttpServletRequest  request=context.getRequest();
        Object token=request.getParameter("token");
        if(token==null){
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
        }else {
            /** 校验 token 真实性（考虑性能）*/

        }
        //添加Basic Auth认证信息
        context.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials("app01", "*****"));
        return null;
    }

    private String getBase64Credentials(String username, String password) {
        String plainCreds = username + ":" + password;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        return new String(base64CredsBytes);
    }
}
